package cn.kennylee.codehub.mongodb.das.config;

import cn.kennylee.codehub.common.das.DasDbType;
import cn.kennylee.codehub.common.das.DasStrategyFactory;
import cn.kennylee.codehub.mongodb.das.extension.MongodbDasQueryStrategy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;

/**
 * <p> MongoDB-DAS自动配置 </p>
 * <p>Created on 2025/2/5.</p>
 *
 * @author kennylee
 * @since 0.0.1
 */
@Configuration
public class MongoDbDasAutoConfig implements SmartInitializingSingleton, ApplicationContextAware {

    private ApplicationContext applicationContext;

    /**
     * 实例化MyBatis查询策略
     *
     * @return MongodbDasQueryStrategy
     */
    @Bean
    @ConditionalOnMissingBean
    @SuppressWarnings("rawtypes")
    public MongodbDasQueryStrategy mongodbDasQueryStrategy() {
        return new MongodbDasQueryStrategy();
    }

    /**
     * 注册MyBatis查询策略到DasStrategyFactory
     */
    @Override
    @SuppressWarnings({"unchecked"})
    public void afterSingletonsInstantiated() {
        // 注册MyBatis查询策略
        DasStrategyFactory.getInstance().registerStrategy(DasDbType.MONGODB, applicationContext.getBean(MongodbDasQueryStrategy.class));
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
